<?php
/**
 * Created by PhpStorm.
 * User: lwt
 * Date: 4/22/19
 * Time: 6:27 PM
 */

namespace app\admin\controller;
use think\Request;
use app\admin\model\UserModel;

class User
{
	 public function file(){
    	$config = [
            'size' => 2097152,
            'ext'  => 'jpg,gif,png,bmp,txt,zip'
        ];
        $request = Request::instance();
        $file = $request->file("co_img");
        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $save_path   = '/uploads/';
        $info        = $file->validate($config)->move($upload_path);
      if ($info) {
        $img = str_replace('\\', '/', $save_path . $info->getSaveName());
        $result = [
                'code'   => 200,
                'msg' => $img
            ];
            return json($result);
      }else{
       $result = [
                'code'   => 400,
                'msg' => $file->getError()
            ];
            return json($result);
      }
    }
    public function login(){
        $request = Request::instance();
        $msg = array();
        $data = $request->param();
        //獲取當前時間
        $time = time();
        $data["ad_login_time"] = $time;
        switch (UserModel::selectAdmin($data)){
            case 0: //账号未注册
                $msg["code"] = 400;
                $msg["msg"] = "账号不存在！";
                return json($msg);
            case 1: //登录成功
                //生產token
                $token = makeToken($data["ad_id"],$time,3600);
                $msg["code"] = 200;
                $msg["msg"] = "登录成功！";
                $msg["token"] = $token;
                return json($msg);
            case 2: //密码错误
                $msg["code"] = 400;
                $msg["msg"] = "密码错误！";
                return json($msg);
        }
    }

    public function selectAdmin(){
        $request = Request::instance();
        $data = $request->post();
        $isToken = isToken($request->get(),$request->get("token"));
        if ($isToken["code"] != 200){
            return json($isToken);
        }
        $content = tokenVerification($request->get("token"));
        if($content["code"] != 200){
            return json($content);
        }
        $msg = UserModel::selectAdminMsg($data["ad_id"]);
        return json($msg);
    }

    public function updateAdmin(){
        $request = Request::instance();
        $data = $request->post();
        $isToken = isToken($request->get(),$request->get("token"));
        if ($isToken["code"] != 200){
            return json($isToken);
        }
        $content = tokenVerification($request->get("token"));
        if($content["code"] != 200){
            return json($content);
        }
        $msg = UserModel::updateAdminMsg($data);
        return json($msg);
    }
}